﻿using System;
using System.Collections.Generic;
using System.Data.Linq;
using System.Linq;
using CoreLibrary;
using CoreLibrary.Repo;
using CoreLibrary.Sql.Ext;
using Entities.DataBase.Obj;
using Entities.DataBase.Persistent;
using Entities.Enumeration;

namespace Entities.DataBase.Impl {

    public class OrderRecordRepository : BaseRepository<OrderRecord>, IOrderRecordRepository {

        private static readonly Func<DataContext, IQueryable<OrderRecord>>
            LinqGetCompleteOrders = CompiledQuery.Compile((DataContext context)
              => (
                  from order  in context.GetTable<Order>().Where(o => o.Status == OrderStatus.Complete)
                  join record in context.GetTable<OrderRecord>()
                  on order.Guid equals record.OrderId
                  select record
            )
        );

        public override string TableName {
            get {
                return "D_ORDER_RECORD";
            }
        }

        public void InsertAll(List<OrderRecord> records) {
            Execute(context => context.InsertAll(records));
        }

        public void Add(OrderRecord record) {
            Execute((context, ts) => context.GetTable<OrderRecord>().InsertOnSubmit(record));
        }

        public List<OrderRecord> ListRecords(string customerId) {
            return Execute(context => context.GetTable<OrderRecord>().Where(o => o.CustomerId.Equals(customerId)).ToList());
        }

        public List<OrderRecord> ListCompleteRecords() {
            return Execute(context => LinqGetCompleteOrders(context).ToList());
        }

        public List<OrderRecord> ListRecordsByOrderGuid(string orderGuid) {
            return Execute(context => context.GetTable<OrderRecord>().Where(o => o.OrderId.Equals(orderGuid)).ToList());
        }

        public OrderRecordSummary GetRecordSummary(int stockId) {
            return Execute(context => {
                var records = context.GetTable<OrderRecord>().Where(o => o.StockId == stockId).ToList();
                if (CollectionUtil.IsEmpty(records)) {
                    return new OrderRecordSummary {
                        TotalCost        = 0,
                        TotalPostage     = 0,
                        TotalNumOfOrders = 0
                    };
                }

                return new OrderRecordSummary {
                    TotalCost        = (double) records.Sum(r => r.Cost),
                    TotalPostage     = (double) records.Sum(r => r.Postage),
                    TotalNumOfOrders = records.Sum(r => r.Count)
                };

            });
        }
    }
}